package org.example.core.utils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Slf4j
public class OkHttpUtils {
    private OkHttpUtils() {}
    private static volatile OkHttpClient okHttpClient;
    public static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8";

    /**
     * 保证单例
     */
    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null){
            synchronized (OkHttpUtils.class){
                if (okHttpClient == null){
                    okHttpClient = new OkHttpClient().newBuilder()
                            .connectTimeout(60, TimeUnit.SECONDS)
                            .writeTimeout(60, TimeUnit.SECONDS)
                            .readTimeout(60, TimeUnit.SECONDS)
                            .build();
                }
            }
        }
        return okHttpClient;
    }
//    public static OkHttpClient getOkHttpClient() {
//        if (okHttpClient == null){
//            synchronized (OkHttpUtils.class){
//                if (okHttpClient == null){
////                    TrustManager[] trustManagers = buildTrustManagers();
//                    okHttpClient = new OkHttpClient().newBuilder()
//                            .connectTimeout(60, TimeUnit.SECONDS)
//                            .writeTimeout(60, TimeUnit.SECONDS)
//                            .readTimeout(60, TimeUnit.SECONDS)
////                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
//                            .hostnameVerifier((hostName, session) -> true)
//                            .retryOnConnectionFailure(true)
//                            .build();
//                }
//            }
//        }
//        return okHttpClient;
//    }

    /**
     * get请求
     * @param url
     * @return
     */
    public static String get(String url) {
        Request rest = new Request.Builder().url(url).get().build();
        return request(url, rest);
    }

    /**
     * get请求带参数
     * @param url
     * @return
     */
    public static String get(String url, Map<String, String> params) {
        HttpUrl.Builder newBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        // 添加参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            newBuilder.addQueryParameter(entry.getKey(), entry.getValue());
        }
        Request rest = new Request.Builder().url(newBuilder.build()).build();
        return request(url, rest);
    }

    /**
     * post请求
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String,String> params){
        RequestBody requestBody = RequestBody.create(JSON.toJSONString(params), MediaType.parse(MEDIA_TYPE_JSON));
        Request rest = new Request.Builder().url(url).post(requestBody).build();
        return request(url, rest);
    }

    /**
     * 处理请求
     * @param url
     * @param request
     * @return
     */
    public static String request(String url, Request request){
        OkHttpClient httpClient = getOkHttpClient();
        try(Response response = httpClient.newCall(request).execute()){
            if (response.isSuccessful()){
                return response.body().string();
            }
        }catch (Exception e){
            log.error("response error.url{}", url, e);
        }
        return null;
    }


    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     *
     * @return
     */
//    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
//        SSLSocketFactory ssfFactory = null;
//        try {
//            SSLContext sc = SSLContext.getInstance("SSL");
//            sc.init(null, trustAllCerts, new SecureRandom());
//            ssfFactory = sc.getSocketFactory();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return ssfFactory;
//    }
//
//    private static TrustManager[] buildTrustManagers() {
//        return new TrustManager[]{
//                new X509TrustManager() {
//                    @Override
//                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
//                    }
//
//                    @Override
//                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
//                    }
//
//                    @Override
//                    public X509Certificate[] getAcceptedIssuers() {
//                        return new X509Certificate[]{};
//                    }
//                }
//        };
//    }
}
